package com.ssy.wireless.task;

import com.ssy.wireless.entity.MessageAuthStat;
import com.ssy.wireless.mapper.MessageAuthStatMapper;
import com.ssy.wireless.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * Created by cofey on 16/11/22.
 */
@Component
@Slf4j
public class MessageAuthStatTask {

    @Autowired
    private MessageAuthStatMapper messageAuthStatMapper;

    //每天整点执行一次
    @Scheduled(cron = "0 0 0/1 * * ?")
    @Transactional
    public void exec() {
        Date dateTime = DateUtils.getTime();
        log.info("短信认证统计任务,{}开始执行...", DateUtils.formatYMDHMS(dateTime));
        Date beginTime = DateUtils.minuteSubtract(dateTime, 60);
        Date endTime = dateTime;
        DateUtils.YearMonthWeekDayHour yearMonthWeekDay = DateUtils.getYearMonthWeekDay(dateTime);
        List<MessageAuthStat> authStats = messageAuthStatMapper.selectStatGroupByHotspot(beginTime, endTime);
        if (CollectionUtils.isEmpty(authStats)) {
            log.info("未找到短信认证记录信息,无需统计");
            return;
        }
        for (MessageAuthStat authStat : authStats) {
            int requestCount = 0, sendCount = 0, loginCount = 0;
            switch (authStat.getType().intValue()) {
                case 1:
                    requestCount = authStat.getStatCount();
                    break;
                case 2:
                    sendCount = authStat.getStatCount();
                    break;
                default:
                    loginCount = authStat.getStatCount();
                    break;
            }
            MessageAuthStat stat = new MessageAuthStat();
            stat.setHourVal(yearMonthWeekDay.getHour());
            stat.setDayVal(yearMonthWeekDay.getDay());
            stat.setWeekVal(yearMonthWeekDay.getWeek());
            stat.setMonthVal(yearMonthWeekDay.getMonth());
            stat.setYearVal(yearMonthWeekDay.getYear());
            stat.setCreateTime(dateTime);
            stat.setRequestCount(requestCount);
            stat.setSendCount(sendCount);
            stat.setLoginCount(loginCount);
            stat.setHotspotId(authStat.getHotspotId());
            messageAuthStatMapper.insert(stat);
        }
        log.info("短信认证统计任务执行成功");
    }
}
